<?php

namespace App\Services\Questions\Type;

use App\Models\Question;
use App\Services\Questions\BaseQuestion;
use Illuminate\Http\Request;

class Radio extends BaseQuestion
{
    /**
     * 单选题添加
     *
     * @param Request $request
     * @return mixed|void
     */
    public function store(Request $request)
    {
        $request->validate($this->validate($request));

        parent::store($request);
    }

    /**
     * 单选题修改
     *
     * @param Request $request
     * @param Question $question
     * @return mixed|void
     */
    public function update(Request $request, Question $question)
    {
        $request->validate($this->validate($request));

        parent::update($request, $question);
    }

    /**
     * 单选题验证规则
     *
     * @param $request
     * @return array
     */
    public function validate($request)
    {
        $keys = [];
        if (is_array($request->input('answer'))) {
            $keys = array_keys($request->input('answer'));
        }

        return [
            'content' => ['required'],
            'answer' => ['bail', 'required', 'array', function ($attr, $value, $f) use ($keys) {
                // 数组排序 ascll 65-90 转 A-Z
                asort($keys);

                if ((array_shift($keys) < 65) || (array_pop($keys) > 90)) {
                    $f($attr . '参数无效');
                }

                if (count($keys) > 26) {
                    $f($attr . '参数无效');
                }
            }],
            'pid' => ['sometimes', 'exists:questions,id,type,subsystem'],
            'success_answer' => ['required', 'required_with:answer', 'integer', function ($attr, $value, $f) use ($keys) {
                if (!collect($keys)->contains($value)) {
                    $f('答案必须在answer中');
                }
            }],
        ];
    }
}
